package logic

import (
	"context"
	"edu-pro/models/cache"
	"edu-pro/pkg"
	"errors"
	"math/rand"
	"strconv"
	"time"

	"edu-pro/edurpc/edurpc"
	"edu-pro/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *edurpc.SendSmsRequest) (*edurpc.SendSmsResponse, error) {
	// 发送短信验证码
	once, _ := cache.RDB.Get(l.ctx, "once"+in.Phone).Int64()
	if once == 1 {
		return nil, errors.New("1 分钟内同一手机号仅能发送 1 次验证码")
	}
	if len(in.Phone) != 11 {
		return nil, errors.New("您输入的手机号码格式有误")
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New(sms.Msg)
	}
	cache.RDB.Set(l.ctx, "sendSms"+in.Phone, code, time.Minute*5)
	cache.RDB.Set(l.ctx, "once"+in.Phone, 1, time.Minute*1)

	return &edurpc.SendSmsResponse{}, nil
}
